﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LogCat.Utility
{
    class ConfigUtility
    {
        static string Tag = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;

        private static string xmlPath = IOUtility.DataPath+"config.xml";

        private static ConfigInfo _config = null;
        public static ConfigInfo config {
            get { 
                if(_config == null){
                    _config = load();
                }
                return _config;
            }

            set {
                _config = value;
            }
        }

        //文件使用的编码类型
        public static StringParseUtility.EncodeType encode
        {
            get {
                return StringParseUtility.EncodeType.GBK;
            }
        }

        //保存配置文件
        public static void save(ConfigInfo info){

            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(dec);
            //创建一个根节点（一级）
            XmlElement root = doc.CreateElement("Config");

            XmlElement log_raw = doc.CreateElement("log_raw");
            log_raw.SetAttribute("value", info.log_raw);
            root.AppendChild(log_raw);

            XmlElement log_rule = doc.CreateElement("log_rule");
            log_rule.SetAttribute("value", info.log_rule);
            root.AppendChild(log_rule);

            XmlElement sql_defult = doc.CreateElement("sql_default");
            sql_defult.SetAttribute("value", info.sql_defult);
            root.AppendChild(sql_defult);

            doc.AppendChild(root);
            doc.Save(xmlPath);
        }

        //加载配置
        public static ConfigInfo load() {

            ConfigInfo info = new ConfigInfo();

            try 
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlPath);

                XmlNode root = doc.SelectSingleNode("Config");
                XmlElement log_raw = (XmlElement)root.SelectSingleNode("log_raw");
                XmlElement log_rule = (XmlElement)root.SelectSingleNode("log_rule");
                XmlElement sql_default = (XmlElement)root.SelectSingleNode("sql_default");

                info.log_raw = log_raw.GetAttribute("value");
                info.log_rule = log_rule.GetAttribute("value");
                info.sql_defult = sql_default.GetAttribute("value");            
            }
            catch(Exception e){
                Log.i(Tag,e.Message);
            }

            return info;
        }
    }
}
